﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MdbPhoneBook.Entities;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using ServiceStack.Redis;

namespace MdbPhoneBook.Dal
{
    public class EmployeesReadDal
    {
        public static int m_Counter = 0;
        private readonly MongoServer m_MonogServer;


        public EmployeesReadDal()
        {
            m_MonogServer = InitMongoServer();
        }

        public List<Employee> GetEmployees()
        {
            var database = m_MonogServer.GetDatabase("PhoneBookDb"); // "test" is the name of the database

            var users =
                database.GetCollection("users")
                    .FindAll()
                    .SetSortOrder(SortBy.Ascending("name"))
                    .SetFields(Fields.Exclude("_id"));

            var l = users
                .AsQueryable()
                .Select(
                    doc =>
                        new Employee(doc["name"].ToString(), doc["phone"].ToString(), doc["birth"].ToString(),
                            doc["ext"].ToString()));

            var list = l.ToList();
            return list;
        }


        private static MongoServer InitMongoServer()
        {
            var connectionString = "mongodb://localhost";
            var client = new MongoClient(connectionString);

            var server = client.GetServer();
            return server;
        }

     
        public List<Employee> GetFilteredEmployees(string employeeName)
        {
            var database = m_MonogServer.GetDatabase("PhoneBookDb"); 

            var q = Query.EQ("name", new BsonRegularExpression(employeeName, "i"));

            var users =
                database.GetCollection("users").Find(query: q)
                    .SetSortOrder(SortBy.Ascending("name"))
                    .SetFields(Fields.Exclude("_id"));

            var l = users
                .AsQueryable()
                .Select(
                    doc =>
                        new Employee(doc["name"].ToString(), doc["phone"].ToString(), doc["birth"].ToString(),
                            doc["ext"].ToString()));

            var list = l.ToList();
            return list;
        }
    }
}
